﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using OPC.Common;
using OPC.Data;

namespace SimpleSim
{
    public partial class Form1 : Form
    {
        private string serverProgID = "Matrikon.OPC.Simulation.1";

        private OpcServer opcServer;
        private OpcGroup opcGroup;
        private OPCItemDef[] opcItemDefs;
        private int[] serverHandles = {0, 0};

        public Form1()
        {
            InitializeComponent();

            opcServer = new OpcServer();
            opcServer.Connect(serverProgID);

            Thread.Sleep(500);

            opcGroup = opcServer.AddGroup("SimpleSim-Group", false, 900);

            opcItemDefs = new OPCItemDef[2];
            opcItemDefs[0] = new OPCItemDef("Random.Real4", true, 1234, VarEnum.VT_EMPTY);
            opcItemDefs[1] = new OPCItemDef("Bucket Brigade.Real4", true, 5678, VarEnum.VT_EMPTY);


            OPCItemResult[] opcItemResults;
            opcGroup.AddItems(opcItemDefs, out opcItemResults);
            foreach (var opcItemResult in opcItemResults)
            {
                if(HRESULTS.Failed(opcItemResult.Error))
                {
                    Debug.Print("OPC Test: AddTimes - some failed");
                    opcGroup.Remove(true);
                    opcServer.Disconnect();
                    return;
                }
            }

            for (int i = 0; i < serverHandles.Count(); i++)
            {
                serverHandles[i] = opcItemResults[i].HandleServer;
            }

            opcGroup.SetEnable(true);
            opcGroup.Active = true;
            opcGroup.DataChanged += OpcGroupDataChanged;
            opcGroup.ReadCompleted += OpcGroupReadCompleted;

        }

        private void OpcGroupReadCompleted(object sender, ReadCompleteEventArgs e)
        {
            
        }

        private void OpcGroupDataChanged(object sender, DataChangeEventArgs e)
        {

        }
    }
}
